<template>
	<div>
		<el-button v-if='tarMsg.deleteBtn && !tarMsg.readonly' style="margin-bottom: 12px;" @click="handleSelect()" type="success" icon="el-icon-plus">添加股票</el-button>
		<el-table stripe :height="list.length > 10 ? 500 : ''" :data="list" v-loading="listLoading" element-loading-text="加载中..." border fit highlight-current-row style="width: 100%">
			<el-table-column type="index" width="40" align="center"></el-table-column>
			<el-table-column prop="code" label="股票代码" align="center"></el-table-column>
			<el-table-column prop="name" label="股票名称" align="center"></el-table-column>
	    	<el-table-column label="相关度" align="center">
		        <template slot-scope="scope">
		        	<el-rate v-model="scope.row.similar" :disabled='tarMsg.readonly || !tarMsg.deleteBtn'></el-rate>
		        </template>
	    	</el-table-column>
	      	<el-table-column v-if='tarMsg.deleteBtn && !tarMsg.readonly' align="center" label="操作" width="150" class-name="small-padding fixed-width">
		        <template slot-scope="scope">
		          	<el-button style="width: auto" type="danger" size="mini" @click.native.prevent="deleteRow(scope.row)">删除</el-button>
		        </template>
	      	</el-table-column>
		</el-table>
		<div class="pagination-container" style="margin-top: 10px;">
			<el-pagination 
				background 
				@size-change="handleSizeChange" 
				@current-change="handleCurrentChange" 
				:current-page.sync="listQuery.pageNum" 
				:page-sizes="[10, 20, 30, 50]" 
				:page-size="listQuery.pageSize" 
				layout="total, sizes, prev, pager, next, jumper" 
				:total="total">
			</el-pagination>
		</div>
  		<el-dialog append-to-body title="相关股票" :visible.sync="dialogVisible" style="text-align: center" :close-on-click-modal=false>
          	<el-form-item label="查询股票" @keyup.enter.native="searchStock(stockSearch)">
                <el-input v-model="stockSearch" type="text" placeholder="请输入">
                  	<el-button slot="append" icon="el-icon-search" @keyup.enter.native="searchStock(stockSearch)" @click='searchStock(stockSearch)'></el-button>
                </el-input>
          	</el-form-item>
          	<el-transfer
                style="text-align: left; display: inline-block"
                v-model="transferData"
                :titles="['股票列表', '已选择']"
                :button-texts="['移除', '添加']"
                :format="{noChecked: '${total}',hasChecked: '${checked}/${total}'}"
            	@change="transferChange"
                :data="stockLib">
          	</el-transfer>
        </el-dialog>
	</div>
</template>

<script>
	import { articleStockList } from '@/api/article'
	import { selectByIdStocks, selectByScStock, selectByRelStock, delStock } from '@/api/events'

	export default {
		name: 'stocksTable',
		props: ['evtMsg'],
		data() {
			return {
				tarMsg: {},
				list: [],
				listLoading: false,
				listQuery: {
					pageNum: 1,
					pageSize: 20,
					eventId: ''
				},
				total: 0,
				dialogVisible: false,
				stockSearch: '',
				stockLib: [],
				transferData: []
			}
		},
		created() {
			this.tarMsg = Object.assign({}, this.evtMsg)
			this.chooseFunc(this.tarMsg.apiTar)
		},
		methods: {
      		chooseFunc(str) {
	    		switch (str) {
		          case 'selectByIdStocks':
		            return this.getList01()
		          case 'selectByScStock':
		            return this.getList02()
		          case 'selectByRelStock':
		            return this.getList03()
		        }
	      	},
			getList01() {
				this.listLoading = true
				this.listQuery.eventId = this.tarMsg.evtId
				selectByIdStocks(this.listQuery).then(res => {
					this.listLoading = false
					this.list = res.Data
					this.total = parseInt(res.total)
				})
			},
			getList02() {
				this.listLoading = true
				this.listQuery.eventId = this.tarMsg.evtId
				selectByScStock(this.listQuery).then(res => {
					this.listLoading = false
					this.list = res.Data
					this.total = parseInt(res.total)
				})
			},
			getList03() {
				this.listLoading = true
				this.listQuery.eventId = this.tarMsg.evtId
				selectByRelStock(this.listQuery).then(res => {
					this.listLoading = false
					this.list = res.Data
					this.total = parseInt(res.total)
				})
			},
			handleSizeChange(val) {
				this.listQuery.pageSize = val
				this.chooseFunc(this.tarMsg.apiTar)
			},
			handleCurrentChange(val) {
				this.listQuery.pageNum = val
				this.chooseFunc(this.tarMsg.apiTar)
			},
			handleSelect() {
		        this.stockSearch = ''
		        this.stockLib = this.list.map(e => {
		         	return {
		            	key: e.name + '(' + e.code + ')',
		            	label: e.name+ '(' + e.code + ')',
		            	similar: e.similar || 0
		          	}
		        })
		        this.transferData = this.list.map(e => { return e.name + '(' + e.code + ')' })
		        this.dialogVisible = true
		  	},
			deleteRow(row) {
		        this.$confirm('确认删除, 是否继续?', '提示', {
		         	confirmButtonText: '确定',
		          	cancelButtonText: '取消',
		          	type: 'warning'
		        }).then(() => {
		        	let obj = {
		        		'id': row.id
		        	}
					delStock(obj).then(res => {
						this.chooseFunc(this.tarMsg.apiTar)
						this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 5000 })
					})
		        }).catch(() => {
		          	this.$message({ type: 'info', message: '已取消删除' })
		        })
	     	},
			searchStock(e) {
		        if (e.trim() === '') {
		          this.$message({ type: 'warning', message: '请输入有效查询内容！' })
		          return
		        }
		        const params = {
		          	pageNum: 1,
		          	pageSize: 99999,
		          	phoneticChars: e
		        }
		        articleStockList(params).then(response => {
		          	const stocks = []
		          	this.list.forEach(e => {
		            	stocks.push(e.code)
		          	})
		          	response.Data.map(e => {
			            if (stocks.indexOf(e.code) === -1) {
			              this.stockLib.push({
			                	key: e.name + '(' + e.code + ')',
			                	label: e.name + '(' + e.code + ')',
			                	similar: 0
			              })
			              return e
			            }
		          	})
		        })
	      	},
			transferChange(value, direction, movedKeys){  //当前值， 数据移动的方向， 发生移动的数据key数组
				if(direction == 'right'){
					movedKeys.map(tar => {
						let obj = {
							code: tar.substring(tar.indexOf("(") + 1, tar.indexOf(")")),
					 		name: tar.split('(')[0],
					 		similar: 0
						}
						return this.list.push(obj)
					})
				} else if(direction == 'left') {
					movedKeys.forEach(val => {
						let valcode = val.substring(val.indexOf("(") + 1, val.indexOf(")"))
						this.list.forEach((item, index) => {
							if(item.code == valcode){
								this.list.splice(index, 1);
							}
						})
					})
				}
			}
		}
	}
</script>

<style scoped>
</style>